package com.rayo.accesscontrollercopy.module.setting;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Environment;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.github.johnkil.print.PrintDrawable;
import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.style.Wave;
import com.litesuits.common.utils.HexUtil;
import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.ActivityManager;
import com.rayo.accesscontrollercopy.app.BaseFragmentActivity;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.module.setting.view.ISettingView;
import com.rayo.accesscontrollercopy.utils.CancelUtils;
import com.rayo.accesscontrollercopy.utils.NetWorkUtils;
import com.rayo.keyholder.data.KeyHolderData;
import com.rayo.keyholder.serialport.KeyHolderService;
import com.rayo.wallreader.utils.TimeUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.rayo.accesscontrollercopy.module.main.MainActivity.mKeyHolderService;


/**
 * Created by yanghaojie on 16/7/21.
 */
public class SettingActivity extends BaseFragmentActivity implements ISettingView {
    private FragmentTabHost mFragmentTabHost;
    private String mTabText[];
    private Drawable mTabImage[];
    private Class mFragmentArray[];

    private View mView;
    private Dialog mDialog;
    private Button mButton;
    private SpinKitView mSpinKitView;
    private Subscription sercuritySp;
    private byte address;
    @Override
    protected int getLayoutId() {
        ActivityManager.getInstance().putActivity(getClass().getSimpleName(), this);
        return R.layout.activity_setting;
    }

    @Override
    protected void setupViews() {
        mTabText = new String[]{getString(R.string.setting_network), getString(R.string.setting_param),getString(R.string.key)};
        //,getString(R.string.setting_reader), getString(R.string.setting_report)
        mTabImage = new Drawable[]{getDrawableIcon(R.string.ic_wifi_tethering), getDrawableIcon(R.string.ic_settings),getDrawableIcon(R.string.ic_key)};
        //,getDrawableIcon(R.string.ic_cast_connected), getDrawableIcon(R.string.ic_event)
        mFragmentArray = new Class[]{NetworkFragment.class, ParamFragment.class,KeyFragment.class};
        //,ReaderFragment.class, EventFragment.class
        mFragmentTabHost = (FragmentTabHost) findViewById(R.id.tab_setting);
        mFragmentTabHost.setup(this, getSupportFragmentManager(), R.id.fl_setting);
        for (int i = 0; i < mTabText.length; i++) {
            TabHost.TabSpec spec = mFragmentTabHost.newTabSpec(mTabText[i]).setIndicator(getTabView(i));
            mFragmentTabHost.addTab(spec, mFragmentArray[i], null);
            mFragmentTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tab_selector);
        }
    }

    @Override
    protected void initialized() {
        GlobalVariables.getInstance().setAndroidId(NetWorkUtils.getAndroidId(getContext()));


    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mKeyHolderReceiver,makeUpdateIntentFilter());
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mKeyHolderReceiver);

    }

    private IntentFilter makeUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(KeyHolderService.ACTION_DATA_READ);
        intentFilter.addAction(KeyHolderService.ACTION_DATA_WRITE);
        intentFilter.addAction(KeyHolderService.ACTION_CLOSE);
        return intentFilter;
    }
    @Override
    public void onClick(View v) {

    }

    private View getTabView(int i) {
        View view = View.inflate(this, R.layout.tab_content, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.img_tab);
        TextView textView = (TextView) view.findViewById(R.id.txt_tab);
        imageView.setImageDrawable(mTabImage[i]);
        textView.setText(mTabText[i]);
        return view;
    }

    private Drawable getDrawableIcon(int resId) {
        StateListDrawable drawable = new StateListDrawable();
        drawable.addState(new int[]{android.R.attr.state_selected}, new PrintDrawable.Builder(this)
                .iconTextRes(resId).iconSizeRes(R.dimen.main_bottom_icon_selected).iconColorRes(R.color.colorAccent).build());
        drawable.addState(new int[]{android.R.attr.state_enabled}, new PrintDrawable.Builder(this)
                .iconTextRes(resId).iconSizeRes(R.dimen.main_bottom_icon).iconColorRes(R.color.Gery).build());
        return drawable;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CancelUtils.unsubscribe(sercuritySp);
        ActivityManager.getInstance().removeActivity(this.getClass().getSimpleName());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                finish();
                break;
            case KeyEvent.KEYCODE_HOME:
                finish();
                break;
            case KeyEvent.KEYCODE_MENU:
                break;
            default:
                break;
        }
        return false;
    }


    @Override
    public void showProgressBar(boolean isShow) {

    }

    @Override
    public void showSnackBar(String txt) {

    }

    @Override
    public void showAlertDialog(String txt) {

    }
    private BroadcastReceiver mKeyHolderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder stringBuilder = new StringBuilder(64);
            final String action = intent.getAction();
            if (intent.getSerializableExtra(KeyHolderService.EXTRA_DATA) instanceof Integer) {
                return;
            }
            final KeyHolderData keyHolderData = (KeyHolderData) intent.getSerializableExtra(KeyHolderService.EXTRA_DATA);
            switch (action) {
                case KeyHolderService.ACTION_DATA_WRITE:
                    stringBuilder.append("SettingSend:");
                    stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));
//                    Log.e("write", stringBuilder.toString());
                    break;
                case KeyHolderService.ACTION_DATA_READ:
                    stringBuilder.append("SettingRead:");
                    stringBuilder.append(String.format("%02X", keyHolderData.getCmd()) + "-");
                    stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));
                    if (keyHolderData.getCmd() == (byte) 0x0b) {
                        if (HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("01")) {

                            if (HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("00", 16)) {

                            } else if (HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("01", 16)) {
                                showWarning(getString(R.string.illegally_open));
                            } else if (HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("02", 16)) {
                                showWarning(getString(R.string.illegally_moved));
                            } else if (HexUtil.encodeHexStr(keyHolderData.getData()).startsWith("03", 16)) {
                                showWarning(getString(R.string.illegally_open) + "、" + getString(R.string.illegally_moved));
                            }

                        } else {

                        }
                    }
//                    Log.e("read", stringBuilder.toString());
                    break;
                case KeyHolderService.ACTION_CLOSE:
                    break;
                default:
                    break;
            }
        }
    };
    private void showWarning(final String action) {
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
        mView = LayoutInflater.from(this).inflate(R.layout.view_sercurity, null);
        mButton = (Button) mView.findViewById(R.id.btn_view_sercurity_btn);
        mSpinKitView = (SpinKitView) mView.findViewById(R.id.sv_view_sercurity_loading);
        mSpinKitView.setIndeterminateDrawable(new Wave());
        mDialog = new AlertDialog.Builder(this)
                .setTitle(action)
                .setView(mView)
                .setIcon(null)
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            mDialog.dismiss();
                            mDialog = null;
                            CancelUtils.unsubscribe(sercuritySp);
                        }
                        return false;
                    }
                })
                .setCancelable(false)
                .create();
        mDialog.show();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSpinKitView.setVisibility(View.VISIBLE);
                mButton.setVisibility(View.GONE);
                addSecurityLog(TimeUtils.dateToNotYMDHMS(new Date()) + "\n" + action);
            }
        });

    }

    private void addSecurityLog(final String s) {
        CancelUtils.unsubscribe(sercuritySp);
        sercuritySp = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (!Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {

                } else {
                    StringBuilder builder = new StringBuilder("");
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "kmslite/security.txt");
                    if (!file.exists()) {
                        try {
                            file.getParentFile().mkdirs();
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    FileInputStream fileInputStream = null;
                    try {
                        fileInputStream = new FileInputStream(file);
                        int count = 0;
                        byte[] readArray = new byte[1024];
                        while ((count = fileInputStream.read(readArray, 0, 1024)) != -1) {
                            builder.append(new String(readArray, 0, count, "utf-8"));
                        }
                        builder.append("\n" + s + "\n");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    FileOutputStream fileOutputStream = null;
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        fileOutputStream.write(builder.toString().getBytes("utf-8"), 0, builder.toString().getBytes().length);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();

                    } catch (IOException e) {
                        e.printStackTrace();

                    } finally {
                        try {
                            builder = null;
                            fileInputStream.close();
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
                subscriber.onNext("");
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(String s) {
                mKeyHolderService.sendData(new KeyHolderData(address,(byte) 0x0a, new byte[0]));
                mDialog.dismiss();
                mDialog = null;
            }
        });
    }

}
